package com.plako.mapper;

import java.io.File;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.plako.mapper.data.AlertPoint;
import com.plako.mapper.offline.OverlayMapViewer;

public class NewPointDialogActivity extends Activity {

	private static final String CAPTURE_DIR = Environment.getExternalStorageDirectory().getPath() + "/odonym/capture/";
	private static final String JSON_DIR = Environment.getExternalStorageDirectory().getPath() + "/odonym/json/";
	private AlertPoint alertPoint;
	int TAKE_PHOTO_CODE = 0;

	private DrawerLayout mDrawerLayout;
	private List<AlertPoint> points;
	private Uri captureOutputFileUri;
	private String captureName;
	private ImageButton capture;
	private EditText captureEditText;
	private File captureNewFile;
	private Button saveButton;
	private EditText adressEditText;
	private EditText descriptionEditText;
	private RadioGroup rg1;
	private RadioGroup rg2;
	private RadioButton checked;
	private OnCheckedChangeListener listener1 = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			if (checkedId != -1) {
				rg2.setOnCheckedChangeListener(null); // remove the listener before clearing so we don't throw that
														// stackoverflow exception(like Vladimir Volodin pointed out)
				rg2.clearCheck(); // clear the second RadioGroup!
				rg2.setOnCheckedChangeListener(listener2); // reset the listener

				Log.i("back", ((RadioButton) findViewById(rg1.getCheckedRadioButtonId())).getBackground().toString());
				if (checked != null)
					checked.setAlpha(1);
				checked = (RadioButton) findViewById(rg1.getCheckedRadioButtonId());
				((RadioButton) findViewById(rg1.getCheckedRadioButtonId())).setAlpha((float) 0.5);

			}
		}
	};
	private OnCheckedChangeListener listener2 = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			if (checkedId != -1) {
				rg1.setOnCheckedChangeListener(null);
				rg1.clearCheck();
				rg1.setOnCheckedChangeListener(listener1);
				Log.i("back", ((RadioButton) findViewById(rg2.getCheckedRadioButtonId())).getBackground().toString());
				if (checked != null)
					checked.setAlpha(1);
				checked = (RadioButton) findViewById(rg2.getCheckedRadioButtonId());

				((RadioButton) findViewById(rg2.getCheckedRadioButtonId())).setAlpha((float) 0.5);

			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_point_dialog);

		adressEditText = (EditText) findViewById(R.id.adress_edit);
		descriptionEditText = (EditText) findViewById(R.id.comment);

		saveButton = (Button) findViewById(R.id.save);
		Bundle b = getIntent().getExtras();

		alertPoint = (AlertPoint) b.getSerializable("alertPoint");

		SharedPreferences sharedpreferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
		alertPoint.setCreated_by_alias(sharedpreferences.getString("login", ""));
		final double lat = alertPoint.getGmlat();
		final double lng = alertPoint.getGmlng();
		rg1 = (RadioGroup) findViewById(R.id.state_radio_group1);
		rg2 = (RadioGroup) findViewById(R.id.state_radio_group2);
		// rg1.clearCheck();
		// rg2.clearCheck();

		rg1.setOnCheckedChangeListener(listener1);

		rg2.setOnCheckedChangeListener(listener2);

		File newdir = new File(CAPTURE_DIR);
		if (!newdir.isDirectory())
			newdir.mkdirs();

		captureEditText = (EditText) findViewById(R.id.image);
		capture = (ImageButton) findViewById(R.id.capture);

		capture.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				captureName = lat + "-" + lng + ".jpg";
				String file = CAPTURE_DIR + captureName;
				captureNewFile = new File(file);
				try {
					captureNewFile.createNewFile();
				} catch (IOException e) {

					Log.wtf("wtf", "wtf");
				}

				// alertPoint.setPicture(captureName);
				captureOutputFileUri = Uri.fromFile(captureNewFile);

				Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, captureOutputFileUri);

				startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
			}
		});

		saveButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				if (isValidForm()) {
					int chkId1 = rg1.getCheckedRadioButtonId();
					int chkId2 = rg2.getCheckedRadioButtonId();
					int checked = chkId1 == -1 ? chkId2 : chkId1;
					alertPoint.setCatid(Integer.parseInt(((RadioButton) findViewById(checked)).getText().toString()));
					alertPoint.setStreet(adressEditText.getText().toString());
					alertPoint.setPicture(captureEditText.getText().toString());
					alertPoint.setDescription(descriptionEditText.getText().toString());
					OverlayMapViewer.alertPoints.add(alertPoint);

					startActivity(new Intent(v.getContext(), OverlayMapViewer.class));
					// ObjectMapper mapper = new ObjectMapper();
					// try {
					// File jsonDir = new File(JSON_DIR);
					// if (!jsonDir.isDirectory())
					// jsonDir.mkdirs();
					// File jsonFile = new File(JSON_DIR + alertPoint.getGmlat() + "-" + alertPoint.getGmlng()
					// + ".json");
					// jsonFile.createNewFile();
					// mapper.writeValue(jsonFile, alertPoint);
					//
					//
					// } catch (JsonGenerationException e) {
					// // TODO Auto-generated catch block
					// e.printStackTrace();
					// } catch (JsonMappingException e) {
					// // TODO Auto-generated catch block
					// e.printStackTrace();
					// } catch (IOException e) {
					// // TODO Auto-generated catch block
					// e.printStackTrace();
					// }

				}
			}
		});

		// point.setText("" + alertPoint.getPoint().latitudeE6);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
			captureEditText.setText(alertPoint.getGmlat() + "-" + alertPoint.getGmlng() + ".jpg");

			Log.d("CameraDemo", "Pic saved");

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.new_point_dialog, menu);
		return true;
	}

	public boolean isValidForm() {
		boolean isValid = true;

		if (TextUtils.isEmpty(adressEditText.getText().toString())) {
			adressEditText.setError(Html.fromHtml("<font color='red'>" + getString(R.string.error_field_required)
					+ "</font>"));
			adressEditText.requestFocus();
			isValid = false;

		}

		if (TextUtils.isEmpty(captureEditText.getText().toString())) {
			captureEditText.setError(Html.fromHtml("<font color='red'>" + getString(R.string.error_field_required)
					+ "</font>"));
			captureEditText.requestFocus();

			isValid = false;

		}

		return isValid;

	}

}
